package util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.log4j.Logger;

import com.schuxl.htmlobserver.dataobject.Ad;

public class DistanceCalculator {
	
	private static Logger LOGGER = Logger.getLogger(DistanceCalculator.class);
	
	public static final String DURATION = "<duration>";
	public static final String DISTANCE = "<distance>";
	public static final String VALUE_START = "<value>";
	public static final String VALUE_END = "</value>";
	public static final String TEXT_START = "<text>";
	public static final String TEXT_END = "</text>";
	public static final String INVALID_REQUEST = "<status>INVALID_REQUEST</status>";
	
	public static final String MAP_DURATION = "duration";
	public static final String MAP_DISTANCE = "distance";
	public static final String MAP_LINK = "link";
	


	
	
	public static HashMap<String, String> addDistanceAndDuration(String originArg, String destinationArg) {
		
		HashMap<String, String> result = new HashMap<String, String>();
		result.put(MAP_DURATION, "");
		result.put(MAP_DISTANCE, "");
		result.put(MAP_LINK, "");
		
		
		
		String origin = originArg.trim().replaceAll("\\s", "%20");
		String destination = destinationArg.trim().trim().replaceAll("\\s",  "%20");
		
		try {
			URL googleMapsApiUrl = new URL("http://maps.googleapis.com/maps/api/directions/xml?origin="+origin+"&destination="+ destination +"&sensor=false");
			URLConnection yc = googleMapsApiUrl.openConnection();
			BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
	        String inputLine;
	        String text = "";
	        
	        while ((inputLine = in.readLine()) != null) 
	        	text+=inputLine;
	        
	        in.close();
	        if(text.contains(INVALID_REQUEST)) {
	        	LOGGER.warn("Der Ort war ungueltig!!!!!");
	        	return result;
	        }
	        	
	        Pattern durationPattern = Pattern.compile("</step>   <duration>.*</text>   </duration>   <distance>");
	        Pattern distancePattern = Pattern.compile("<text>.{1,20}</distance>   <start_location>");
	        Matcher durationMatcher = durationPattern.matcher(text);
	        Matcher distanceMatcher = distancePattern.matcher(text);
	        if(durationMatcher.find()==false || distanceMatcher.find()==false)
	        	return result;
	        String x = text.substring(durationMatcher.start(), durationMatcher.end());
	        String y = text.substring(distanceMatcher.start(), distanceMatcher.end());
	        int duration = Integer.parseInt(x.substring(x.indexOf(VALUE_START)+VALUE_START.length(), x.indexOf(VALUE_END)));
	        String distance = y.substring(y.indexOf(TEXT_START)+TEXT_START.length(), y.indexOf(TEXT_END));
	        
	        int hours = (int) duration/3600;
	        int minutes = (int) (duration-(hours*3600))/60;

	        result.put(MAP_DISTANCE, distance);
	        result.put(MAP_DURATION, hours+ "h:"+ minutes+"min");
	        result.put(MAP_LINK, "https://maps.google.at/maps?saddr="+origin+"&daddr="+destination+"&hl=de");
		} catch (MalformedURLException e) {
			LOGGER.error("Fehler beim Aufruf der GoogleMapsApiUrl!", e);
		} catch (IOException e) {
			LOGGER.error("Fehler beim Lesen des GoogleMapApi Results!", e);
		} catch(Exception e) {
			LOGGER.error("Fehler bein Parsen des GoogleMapApi Results!", e);
		}
        
		return result;
    }
    
    
}
